package org.wangblue.query;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.wangblue.common.Client;

/**
 * @Description: 排序查询
 * @Author: WangBlue
 * @Create: 2024-10-24 11:10
 * @Version: 1.0
 **/

public class SortQuery {
    private static final String INDEX_NAME = "user";
    public static void main(String[] args) {
        try (RestHighLevelClient client = Client.getClient()) {
            // 1. 创建搜索请求对象
            SearchRequest request = new SearchRequest();
            request.indices(INDEX_NAME);

            // 2. 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.matchAllQuery());

            // 3. 排序
            sourceBuilder.sort("age", SortOrder.DESC);
            request.source(sourceBuilder);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            // 4. 查询匹配
            SearchHits hits = response.getHits();
            System.out.println("took:" + response.getTook());
            System.out.println("timeout:" + response.isTimedOut());
            System.out.println("total:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
            System.out.println("hits========>>");
            for (SearchHit hit : hits) {
                //输出每条查询的结果信息
                System.out.println(hit.getSourceAsString());
            }
            System.out.println("<<========");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
